package com.ziytek.web.citizen.listener;


import com.ziytek.web.citizen.config.caffeine.CaffeineUtil;
import com.ziytek.web.citizen.constant.ServerConstant;
import com.ziytek.web.citizen.event.WholeCommandIssuedEvent;
import com.ziytek.web.citizen.mapper.SettingDetailMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * @author fengh
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class WholeCommandIssuedEventListener {

    private final SettingDetailMapper settingDetailMapper;

    @Async("myAsyncExecutor")
    @EventListener
    @Order(ServerConstant.DATA_TYPE_LEN_1)
    public void wholeCommandIssuedEventListener(WholeCommandIssuedEvent event) {
        Assert.notNull(event, "event can not be null");
        Assert.notNull(event.getStepId(), "event stepId can not be null");
        Assert.notNull(event.getCabinetNo(), "event cabinetNo can not be null");

        log.info("wholeCommandIssuedEventListener,cabinetNo:{},stepId:{}", event.getCabinetNo(), event.getStepId());

        var stepId = event.getStepId();
        var orderNo = event.getOrderNo();
        var cabinetNo = event.getCabinetNo();
        var k = CaffeineUtil.CACHE_KEY_COMMAND_OPERATE_ALL + CaffeineUtil.getCacheKey(cabinetNo.intValue(), 255, 255);

        Integer timeCount = settingDetailMapper.queryTimeCountByStepId(stepId, orderNo);

        var expire = Math.max(timeCount, 0) * 60L + 5;
        log.info("wholeCommandIssuedEventListener cache key: {}, timeCount: {}, expire: {}", k, timeCount, expire);
        CaffeineUtil.set(k, timeCount, expire);
    }
}
